/*
 * Copyright (C) 2018 Hein-Pieter van Braam
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "ResStringPool.h"

char* to_char_string(const uint8_t* data, uint32_t length) {
	char* string = (char*) calloc(length + 1, 1);
	for (int i = 0; i < length; ++i) {
		string[i] = *(data + (i * 2));
	}

	return string;
}

ResStringPool::ResStringPool() :
		_size(0), _strings(nullptr) {
}

ResStringPool::ResStringPool(const uint8_t* data) {
	ResStringPool_header header;
	uint32_t* entries;
	memcpy(&header, data, sizeof(ResStringPool_header));

	if (header.header.type != RES_STRING_POOL_TYPE) {
		printf("Not a ResStringPool!\n");
		return;
	}

	_size = header.stringCount;
	entries = (uint32_t*) (data + header.header.headerSize);
	_strings = (const char**)malloc(_size * sizeof(const char*));

	const uint8_t* stringdata = data + header.stringsStart;

	for (int i = 0; i < _size; ++i) {
		uint32_t offset = entries[i];
		size_t size = *((const uint16_t*)(stringdata + offset));

		if ((size & 0x8000) != 0) {
			offset += 2;
			size = ((size & 0x7FFF) << 16) | *((const uint16_t*)(stringdata + offset));
		}
		offset += 2;

		_strings[i] = to_char_string(stringdata + offset, size);
	}
}

const char* ResStringPool::get(int32_t index) const {
	if (index < 0 || index >= _size) {
		return nullptr;
	}

	return _strings[index];
}

void ResStringPool::dump() {
	for (int i = 0; i < _size; ++i) {
		printf("String %i: '%s'\n", i, _strings[i]);
	}
}

ResStringPool::~ResStringPool() {
	for (int i = 0; i < _size; ++i) {
		free((void*)_strings[i]);
	}
	free(_strings);
}
